const request = require('../utils/request')
const { addSqlForm } = require('../utils/base')
const fs = require('fs')
const path = require('path')
const { successStatus, errorStatus } = require('../utils/status')
const md5 = require('md5')
// 获取用户列表信息
async function userlist (req, res) {
  // res.status(200).json({code: 200, token: req.token}) // 测试接收token使用
  const result = await request(`select username, user_pic, email, nickname from user`)
  if (result) {
    successStatus.RESULT.data = {
      data: result,
      msg: '获取列表成功'
    }
    res.status(200).json(successStatus.RESULT)
  } else {
    errorStatus.RESULT.msg = "获取列表失败，请联系管理员"
    res.status(400).json(errorStatus.RESULT)
  }
}

// 查询用户个人信息
async function userInfo (req, res) {
  const { id } = req.params
  if (req.user && req.user.id != id) return next('查询的不是本用户个人信息')
  try {
    const result = await request(`select username, user_pic, email, nickname from user where id=${id}`)
    if (result.length > 0) {
      let newdata = {
        username : result[0].username,
        user_pic: result[0].user_pic ? 'http://localhost:8000/images/' + result[0].user_pic : null,
        email: result[0].email,
        nickname: result[0].nickname
      }
      successStatus.RESULT.data = {
        msg: '获取用户信息成功',
        data: newdata
      }
      res.status(200).json(successStatus.RESULT)
    }
  } catch (error) {
    errorStatus.RESULT.msg = "获取用户信息失败,请联系管理员"
    res.status(400).json(errorStatus.RESULT)
  }
}

// 更新用户信息
async function userUpdate (req, res) {
  let {id, user_pic = null, username = null, email = null, nickname = null} = req.body
  if (req.user && req.user.id != id) return next('不能修改他人个人信息')
  if (user_pic) {
    let extname = path.extname(user_pic)
    let picName = `${new Date().getTime()}${Math.random().toString().slice(2)}${extname}`
    fs.writeFileSync(path.join(__dirname, '../uploads/')+ picName,fs.readFileSync(user_pic))
    user_pic = picName
  }
  let str = addSqlForm({username, email, nickname, user_pic})
  try {
    const result = await request(`update user set ${str} where id=${id}`)
    if (result.affectedRows > 0) {
      successStatus.RESULT.data = {
        msg: '更新成功'
      }
      res.status(200).json(successStatus.RESULT)
    } else {

    }
  } catch (error) {
    errorStatus.RESULT.msg = '更新用户信息失败,请联系管理员'
    res.status(400).json(resultData)
  }
}

// 删除用户
async function deleteUser (req, res) {
  const { id } = req.params
  try {
    const result = await request(`delete from user where id=${id}`)
    if (result.affectedRows > 0) {
      successStatus.RESULT.data = {
        msg: '删除成功'
      }
      res.status(200).json(successStatus.RESULT)
      next()
    }
  } catch (error) {
    errorStatus.RESULT.msg = '删除用户失败,请联系管理员'
    res.status(400).json(errorStatus.RESULT)
  }
}

// 修改用户密码
async function userUpdatePwd (req, res, next) {
  let {id = null, oldPwd = null, newPwd = null} = req.body
  if (req.user.id != id) return next('不能修改他人用户密码')
  if (!id || !oldPwd || !newPwd) return next('请完整填写参数')
  try {
    const md5OldPwd = md5(oldPwd)
    const userInfo = await request(`select password from user where id=${id}`)
    if (md5OldPwd !== userInfo[0].password) return next('旧密码不正确,请重新输入')
    const md5NewPwd = md5(newPwd)
    const result = await request(`update user set password='${md5NewPwd}' where id=${id}`)
    if (result.affectedRows > 0) {
      successStatus.RESULT.data = {
        msg: '更新密码成功'
      }
      res.status(200).json(successStatus.RESULT)
      next()
    }
  } catch (error) {
    errorStatus.RESULT.msg = '更新用户密码失败,请联系管理员'
    res.status(400).json(errorStatus.RESULT)
  }
}


module.exports = {
  userlist,
  userInfo,
  userUpdate,
  deleteUser,
  userUpdatePwd
}